import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:file_picker/file_picker.dart';
import 'dart:io';

/// Excel状态
abstract class ExcelState {}

class ExcelInitial extends ExcelState {}

class ExcelLoading extends ExcelState {}

class ExcelFileSelected extends ExcelState {
  final File file;
  final String fileName;
  final int fileSize;

  ExcelFileSelected({
    required this.file,
    required this.fileName,
    required this.fileSize,
  });
}

class ExcelUploaded extends ExcelState {
  final String fileName;
  final List<ExcelRowData> data;
  final int totalRows;

  ExcelUploaded({
    required this.fileName,
    required this.data,
    required this.totalRows,
  });
}

class ExcelError extends ExcelState {
  final String message;
  ExcelError(this.message);
}

/// Excel行数据
class ExcelRowData {
  final int rowIndex;
  final Map<String, dynamic> data;

  ExcelRowData({
    required this.rowIndex,
    required this.data,
  });
}

/// Excel状态通知器
class ExcelStateNotifier extends Notifier<ExcelState> {
  @override
  ExcelState build() {
    return ExcelInitial();
  }

  /// 选择Excel文件
  Future<void> pickExcelFile() async {
    try {
      final result = await FilePicker.platform.pickFiles(
        type: FileType.custom,
        allowedExtensions: ['xlsx', 'xls'],
        allowMultiple: false,
      );

      if (result != null && result.files.isNotEmpty) {
        final platformFile = result.files.first;

        if (platformFile.path != null) {
          final file = File(platformFile.path!);

          state = ExcelFileSelected(
            file: file,
            fileName: platformFile.name,
            fileSize: platformFile.size,
          );
        } else {
          state = ExcelError('无法获取文件路径');
        }
      }
    } catch (e) {
      state = ExcelError('选择文件失败：${e.toString()}');
    }
  }

  /// 上传Excel文件
  Future<void> uploadExcelFile(File file) async {
    state = ExcelLoading();

    try {
      // TODO: 实现文件上传到后端
      // final excelRepository = _ref.read(excelRepositoryProvider);
      // final result = await excelRepository.uploadExcel(file);

      // 模拟解析Excel数据
      await Future.delayed(const Duration(seconds: 2));

      final mockData = _generateMockExcelData();

      state = ExcelUploaded(
        fileName: file.path.split('/').last,
        data: mockData,
        totalRows: mockData.length,
      );
    } catch (e) {
      state = ExcelError('上传文件失败：${e.toString()}');
    }
  }

  /// 清空选择的文件
  void clearSelectedFile() {
    state = ExcelInitial();
  }

  /// 重新选择文件
  Future<void> reSelectFile() async {
    state = ExcelInitial();
    await pickExcelFile();
  }

  /// 生成模拟Excel数据
  List<ExcelRowData> _generateMockExcelData() {
    return [
      ExcelRowData(
        rowIndex: 1,
        data: {
          '需求标题': '用户登录功能优化',
          '需求描述': '优化用户登录流程，提升用户体验',
          '优先级': '高',
          '预计工时': '16',
          '负责人': '张三',
          '状态': '待开发',
        },
      ),
      ExcelRowData(
        rowIndex: 2,
        data: {
          '需求标题': '订单管理系统',
          '需求描述': '开发完整的订单管理功能模块',
          '优先级': '中',
          '预计工时': '40',
          '负责人': '李四',
          '状态': '需求分析',
        },
      ),
      ExcelRowData(
        rowIndex: 3,
        data: {
          '需求标题': '数据报表功能',
          '需求描述': '实现各类数据报表的生成和导出',
          '优先级': '低',
          '预计工时': '24',
          '负责人': '王五',
          '状态': '待排期',
        },
      ),
      ExcelRowData(
        rowIndex: 4,
        data: {
          '需求标题': '移动端适配',
          '需求描述': '适配移动端界面和交互体验',
          '优先级': '高',
          '预计工时': '32',
          '负责人': '赵六',
          '状态': '开发中',
        },
      ),
      ExcelRowData(
        rowIndex: 5,
        data: {
          '需求标题': '性能监控',
          '需求描述': '添加系统性能监控和告警功能',
          '优先级': '中',
          '预计工时': '20',
          '负责人': '钱七',
          '状态': '测试中',
        },
      ),
    ];
  }

  /// 生成待办任务建议
  Future<void> generateTodoSuggestions() async {
    final currentState = state;
    if (currentState is! ExcelUploaded) {
      state = ExcelError('请先上传Excel文件');
      return;
    }

    try {
      // TODO: 调用AI服务生成待办任务建议
      // final aiService = _ref.read(aiServiceProvider);
      // final suggestions = await aiService.generateTodoSuggestions(currentState.data);

      // 模拟生成建议
      await Future.delayed(const Duration(seconds: 1));

      // 这里可以触发导航到建议页面或显示建议
      // 目前简单显示成功消息
    } catch (e) {
      state = ExcelError('生成建议失败：${e.toString()}');
    }
  }
}

/// Excel状态Provider
final excelStateProvider =
    NotifierProvider<ExcelStateNotifier, ExcelState>(ExcelStateNotifier.new);

/// 当前选择的文件Provider
final selectedExcelFileProvider = Provider<File?>((ref) {
  final excelState = ref.watch(excelStateProvider);
  if (excelState is ExcelFileSelected) {
    return excelState.file;
  }
  return null;
});

/// Excel数据Provider
final excelDataProvider = Provider<List<ExcelRowData>>((ref) {
  final excelState = ref.watch(excelStateProvider);
  if (excelState is ExcelUploaded) {
    return excelState.data;
  }
  return [];
});

/// 文件信息Provider
final fileInfoProvider = Provider<Map<String, dynamic>?>((ref) {
  final excelState = ref.watch(excelStateProvider);

  if (excelState is ExcelFileSelected) {
    return {
      'fileName': excelState.fileName,
      'fileSize': excelState.fileSize,
      'status': 'selected',
    };
  }

  if (excelState is ExcelUploaded) {
    return {
      'fileName': excelState.fileName,
      'totalRows': excelState.totalRows,
      'status': 'uploaded',
    };
  }

  return null;
});
